<?php

declare (strict_types=1);

namespace app\admin\controller\admin;

use app\admin\controller\Base;
use app\admin\model\admin\Menu as MenuModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\response\Json;

/**
 * 后台菜单管理
 * Class Menu
 */
class Menu extends Base
{
    /**
     * 菜单列表
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function list(): Json
    {
        $model = new MenuModel;
        $list = $model->getList($this->request->param());
        return $this->returnSuccess(compact('list'));
    }

    /**
     * 菜单列表
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function all(): Json
    {
        $model = new MenuModel;
        $list = $model->getAllList($this->request->param());
        return $this->returnSuccess(compact('list'));
    }

    /**
     * 新增菜单
     * @return Json
     */
    public function add(): Json
    {
        // 新增记录
        $model = new MenuModel;
        if ($model->add($this->postForm())) {
            return $this->returnSuccess('添加成功');
        }
        return $this->returnError($model->getError() ?: '添加失败');
    }

    /**
     * 编辑菜单
     * @return Json
     */
    public function edit(): Json
    {
        $postData = $this->postData();
        $menuId = $postData['menuId'];

        // 菜单详情
        $model = MenuModel::detail($postData['menuId']);
        // 更新记录
        if ($model->edit($this->postForm())) {
            return $this->returnSuccess('更新成功');
        }
        return $this->returnError($model->getError() ?: '更新失败');
    }

    /**
     * 设置菜单绑定的Api
     * @return Json
     */
    public function setApis(): Json
    {
        $postData = $this->postData();
        $menuId = $postData['menuId'];

        // 菜单详情
        $model = MenuModel::detail($postData['menuId']);
        // 更新记录
        if ($model->setApis($this->postForm())) {
            return $this->returnSuccess('绑定成功');
        }
        return $this->returnError($model->getError() ?: '绑定失败');
    }

    /**
     * 删除菜单
     * @return Json
     */
    public function deleted(): Json
    {
        $postData = $this->postData();
        $menuId = $postData['menuId'];

        // 菜单详情
        $model = MenuModel::detail($menuId);
        if (!$model->remove()) {
            return $this->returnError($model->getError() ?: '删除失败');
        }
        return $this->returnSuccess('删除成功');
    }
}
